import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Switch, Icon, Input, Button, message as Message, Select, DatePicker } from 'antd'
import moment from 'moment'
const Option = Select.Option;
const FormItem = Form.Item;
import Selector from 'components/selector'
import expenseStandardService from 'containers/expense-reimbursement-control/expense-standard/expense-standard.service'
import LanguageInput from 'components/template/language-input/language-input'
import errorMessage from 'share/errorMessage'
import Chooser from 'components/chooser';
import Condition from 'components/condition';

const { If } = Condition;

class NewExpenseTypeRule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      i18n: {},
      message: '',
      methodList: [
        {value: 'WARNING', messageKey: messages('setting.key1073')/*警告*/},
        {value: 'REJECT', messageKey: messages('setting.key38')/*禁止*/},
      ],
      source: [
        {
          value: 1001,
          name: messages('expense-reimbursement-control.key111')/*账套级*/
        },
        {
          value: 1002,
          name: messages('expense-reimbursement-control.key40')/*公司级*/
        }
      ],
      currencyInit: {
        key: props.company.baseCurrency,
        label: props.company.baseCurrencyName
      }
    };
  }

  onCancel = () => {
    this.props.close();
  };

  componentDidMount(){};

  componentWillReceiveProps(nextProps) {
    let nextData = nextProps.params.nowRule;
    if(nextProps.params.showSlideFrame !== this.props.params.showSlideFrame && nextProps.params.showSlideFrame){
      if(nextData.ruleOID){
        let valueWillSet = this.props.form.getFieldsValue();
        Object.keys(valueWillSet).map(key => {
          valueWillSet[key] = nextData[key];
          if(key.indexOf('Date') > -1 && valueWillSet[key]){
            valueWillSet[key] = moment(valueWillSet[key]);
          }
        });
        this.props.form.setFieldsValue(valueWillSet);
        this.setState({ message: nextData.message, i18n: nextData.i18n })
      } else {
        this.props.form.resetFields();
        this.setState({ message: '', i18n: {} })
      }
    }
  }

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      const { message, i18n } = this.state;
      const { company, expenseTypeSetOfBooks: { id }, tenantMode } = this.props;
      const { expenseTypeOID, nowRule, copy } = this.props.params;
      if (!err) {
        if(!message){
          Message.error(messages('setting.key1524')/*提示内容必填！*/);
          return ;
        }
        values.message = message;
        values.i18n = i18n;
        values.companyOID = company.companyOID;
        tenantMode && (values.setOfBooksId = id);
        values.startDate = values.startDate.utc().format('YYYY-MM-DDTHH:mm:ss') + '.000Z';
        if(values.endDate){
          values.endDate = values.endDate.utc().format('YYYY-MM-DDTHH:mm:ss') + '.000Z';
        }
        if(typeof values.currencyCode === 'object'){
          values.currencyCode = values.currencyCode.key;
        }
        values.entityType = 'INVOICE';
        values.entityOID = expenseTypeOID;
        if(nowRule.ruleOID && !copy){
          values.ruleOID = nowRule.ruleOID;
          values.id = nowRule.id;
        }
        if (copy) { //复制的规则
          values.isCopy = true;
          values.id = nowRule.id
        }
        this.setState({ loading: true });
        expenseStandardService.saveRule(values).then(res => {
          this.setState({ loading: false });
          Message.success(messages('setting.key211')/*保存成功*/);
          this.props.close(true);
        }).catch(e => {
          this.setState({ loading: false });
          errorMessage(e.response)
        })
      }
    });
  };

  handleChangeI18n = (message, i18nData) => {
    const { i18n } = this.state;
    i18n.message = i18nData;
    this.setState({ message, i18n })
  };

  //获取多语言输入框的字符长度
  getInpRule = (num) => {
    let inpRule = [];
    this.props.languageList.map(language => {
      inpRule.push({
        length: num,
        language: language.code.toLowerCase()
      });
    });
    return inpRule;
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    let { methodList, i18n, message, loading, source, currencyInit } = this.state;
    const { company, tenantMode, params: { nowRule }, expenseTypeSetOfBooks: { id, functionalCurrencyCode } } = this.props;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    tenantMode && (currencyInit = functionalCurrencyCode);
    return (
      <div>
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('setting.key1091')/*规则名称*/}>
            {getFieldDecorator('ruleName', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }]
            })(
              <Input maxLength="32"/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1525')/*控制方式*/}>
            {getFieldDecorator('actionType', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: 'WARNING'
            })(
              <Select>
                {
                  methodList.map(item => {
                    return <Option key={item.value}>{item.messageKey}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1181')/*币种*/}>
            {getFieldDecorator('currencyCode', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: currencyInit
            })(
              <Selector type="currency_for_company"
                        params={{
                          setOfBooksId: id
                        }}
                        filter={item => item.enable}
                        showSearch
                        placeholder={messages("common.please.select")}
                        allowClear={false}/>
            )}
          </FormItem>

          <If value={tenantMode}>
            <FormItem {...formItemLayout} label={messages('setting.key730')/*适用公司*/}>
              {getFieldDecorator('companys', {
                initialValue: !tenantMode ? [{
                  companyOID: company.companyOID,
                  name: company.name
                }] : []
              })(
                <Chooser
                  disabled={!tenantMode}
                  placeholder={tenantMode ? messages('expense-reimbursement-control.key28')/*通用*/ : messages('common.please.select')}
                  type='available_company_setOfBooks'
                  labelKey='name'
                  valueKey='companyOID'
                  listExtraParams={{ setOfBooksId: id, enabled: true }}
                  single={false}/>
              )}
            </FormItem>
          </If>

          <FormItem {...formItemLayout} label={messages('expense-reimbursement-control.key112')/*规则来源*/}>
            {getFieldDecorator('source', {
              initialValue: tenantMode ? 1001 : 1002
            })(
              <Select disabled placeholder={messages('common.please.select')}>
                {
                  source.map(item => <Option value={item.value}>{item.name}</Option>)
                }
              </Select>
            )}
          </FormItem>


          <FormItem {...formItemLayout} label={messages('setting.key1526')/*生效时间*/}>
            {getFieldDecorator('startDate', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: moment()
            })(
              <DatePicker/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1527')/*结束时间*/}>
            {getFieldDecorator('endDate')(
              <DatePicker/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1528')/*规则状态*/}>
            {getFieldDecorator('enabled', {
              valuePropName: 'checked',
              initialValue: true
            })(
              <Switch checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="cross" />}/>
            )}&nbsp;&nbsp;&nbsp;&nbsp;{this.props.form.getFieldValue('enabled') ? messages('common.status.enable') : messages('common.status.disable')}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1107')/*提示内容*/} required>
            <LanguageInput textArea
                           i18nName={i18n.message}
                           name={message}
                           nameChange={this.handleChangeI18n}
                           isEdit={!!nowRule.ruleOID}
                           inpRule={this.getInpRule(300)}/>
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')/* 保存 */}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/* 取消 */}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    languageList: state.login.languageList,
    tenantMode: state.main.tenantMode,
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks
  }
}
const WrappedNewExpenseTypeRule = Form.create()(NewExpenseTypeRule);

export default connect(mapStateToProps)(WrappedNewExpenseTypeRule);

